<template>
  <div class="analytics-dashboard min-h-screen">
    <!-- 数据概览卡片 -->
    <el-row :gutter="24" justify="space-around">
      <re-col
        v-for="(item, index) in chartData"
        :key="index"
        class="mb-[18px]"
        :value="6"
        :md="12"
        :sm="12"
        :xs="24"
        :initial="{
          opacity: 0,
          y: 100
        }"
        :enter="{
          opacity: 1,
          y: 0,
          transition: {
            delay: 80 * (index + 1)
          }
        }"
      >
        <el-card class="line-card" shadow="never">
          <div class="flex justify-between">
            <span class="text-md text-gray-600 font-medium">
              {{ item.name }}
            </span>
            <div
              class="w-8 h-8 flex justify-center items-center rounded-md"
              :style="{
                backgroundColor: isDark ? 'transparent' : item.bgColor
              }"
            >
              <IconifyIconOffline :icon="item.icon" :color="item.color" width="18" height="18" />
            </div>
          </div>
          <div class="flex justify-between items-start mt-3">
            <div class="w-1/2">
              <ReNormalCountTo
                :duration="item.duration"
                :fontSize="'1.6em'"
                :startVal="100"
                :endVal="item.value"
              />
              <p class="font-medium text-green-500">{{ item.percent }}</p>
            </div>
            <div class="w-1/2">
              <span>&nbsp;</span>
              <p class="font-600 text-gray-500">总使用量: 1222</p>
            </div>
          </div>
        </el-card>
      </re-col>
    </el-row>
    <!-- 图表区域 -->
    <el-row class="justify-between mb-2">
      <!-- 网站浏览量柱状图 -->
      <el-col :span="16" class="bg-white p-6 mb-[18px] shadow-sm">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-gray-800">网站浏览量统计</h3>
          <el-button-group>
            <el-button
              :type="chartTimeRange === 'day' ? 'primary' : ''"
              size="small"
              @click="changeChartTimeRange('day')"
            >
              日
            </el-button>
            <el-button
              :type="chartTimeRange === 'month' ? 'primary' : ''"
              size="small"
              @click="changeChartTimeRange('month')"
            >
              月
            </el-button>
            <el-button
              :type="chartTimeRange === 'year' ? 'primary' : ''"
              size="small"
              @click="changeChartTimeRange('year')"
            >
              年
            </el-button>
          </el-button-group>
        </div>
        <div ref="barChartRef" class="h-80" />
      </el-col>

      <!-- 访问量排行 -->
      <el-col :span="8" class="bg-white p-6 mb-[18px] shadow-sm">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">访问量排行</h3>
        <div class="space-y-3">
          <div
            v-for="(item, index) in rankingData"
            :key="index"
            class="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
          >
            <div class="flex items-center">
              <div
                class="w-8 h-8 rounded-full flex items-center justify-center text-white font-bold mr-3"
                :class="getRankingColor(index)"
              >
                {{ index + 1 }}
              </div>
              <span class="font-medium text-gray-800">{{ item.name }}</span>
            </div>
            <span class="text-lg font-bold text-gray-600">{{ item.value.toLocaleString() }}</span>
          </div>
        </div>
      </el-col>
    </el-row>

    <div class="grid grid-cols-1 lg:grid-cols-1 gap-6 mb-4">
      <!-- 用户访问趋势折线图 -->
      <div class="bg-white p-6 rounded-lg shadow-sm">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">最近1小时访问情况</h3>
        <div ref="lineChartRef" class="h-80" />
      </div>
    </div>

    <!-- 渠道来源和地域分布 -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
      <!-- 渠道来源饼图 -->
      <div class="bg-white p-6 rounded-lg shadow-sm">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">渠道来源分析</h3>
        <div ref="pieChartRef" class="h-80" />
      </div>
      <!-- 热门搜索词云图 -->
      <div class="bg-white p-6 rounded-lg shadow-sm">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">热门搜索</h3>
        <div ref="wordCloudRef" class="h-80" />
      </div>
      <!-- 地域分布 -->
      <div class="bg-white p-6 rounded-lg shadow-sm">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">地域分布</h3>
        <div ref="mapChartRef" class="h-80" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch, computed, onBeforeMount } from "vue";
import * as echarts from "echarts";
import "echarts-wordcloud";

import ReCol from "@/components/ReCol";
import { ReNormalCountTo } from "@/components/ReCountTo";
import { chartData } from "./data";
import { useDark } from "./utils";
const { isDark } = useDark();
// 响应式数据
const timeRange = ref("month");
const chartTimeRange = ref("month");

// 排行数据
const rankingData = ref([
  { name: "工专路1号店", value: 333001 },
  { name: "工专路2号店", value: 333002 },
  { name: "工专路3号店", value: 333003 },
  { name: "工专路4号店", value: 333004 },
  { name: "工专路5号店", value: 333005 }
]);

// 图表引用
const barChartRef = ref(null);
const lineChartRef = ref(null);
const wordCloudRef = ref(null);
const pieChartRef = ref(null);
const mapChartRef = ref(null);

// 图表实例
let barChart = null;
let lineChart = null;
let wordCloudChart = null;
let pieChart = null;
let mapChart = null;

// 计算属性
const datePickerType = computed(() => {
  const typeMap = {
    day: "date",
    month: "month",
    year: "year"
  };
  return typeMap[timeRange.value];
});

// 柱状图数据
const getBarChartData = () => {
  const monthData = {
    categories: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
    data: [800, 520, 900, 760, 340, 780, 700, 950, 980, 240, 360, 950]
  };

  const dayData = {
    categories: Array.from({ length: 24 }, (_, i) => `${i}:00`),
    data: Array.from({ length: 24 }, () => Math.floor(Math.random() * 1000) + 200)
  };

  const yearData = {
    categories: ["2019", "2020", "2021", "2022", "2023"],
    data: [8500, 9200, 7800, 10500, 11200]
  };

  return chartTimeRange.value === "day" ? dayData : chartTimeRange.value === "month" ? monthData : yearData;
};

// 初始化柱状图
const initBarChart = () => {
  if (!barChartRef.value) return;

  barChart = echarts.init(barChartRef.value);
  const data = getBarChartData();

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: data.categories,
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        name: "访问量",
        type: "bar",
        barWidth: "60%",
        data: data.data,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#83bff6" },
            { offset: 0.5, color: "#188df0" },
            { offset: 1, color: "#188df0" }
          ])
        }
      }
    ]
  };

  barChart.setOption(option);
};
const smallChartRef = ref(null);
let smallLineChart = null;
// 初始化小折线图
const initSmallLineChart = () => {
  const dom = smallChartRef.value;
  if (!dom || dom.offsetWidth === 0) return;
  smallLineChart = echarts.init(dom);
  const option = {
    title: {
      text: "100%",
      left: "47%",
      top: "30%",
      textAlign: "center",
      textStyle: {
        fontSize: "16",
        fontWeight: 600
      }
    },
    polar: {
      radius: ["100%", "90%"],
      center: ["50%", "50%"]
    },
    angleAxis: {
      max: 100,
      show: false
    },
    radiusAxis: {
      type: "category",
      show: true,
      axisLabel: {
        show: false
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    },
    series: [
      {
        type: "bar",
        roundCap: true,
        barWidth: 2,
        showBackground: true,
        backgroundStyle: {
          color: "#dfe7ef"
        },
        data: [100],
        coordinateSystem: "polar",
        color: "#7846e5",
        itemStyle: {
          shadowBlur: 2,
          shadowColor: "#7846e5",
          shadowOffsetX: 0,
          shadowOffsetY: 0
        }
      }
    ]
  };

  smallLineChart.setOption(option);
};
// 初始化折线图
const initLineChart = () => {
  if (!lineChartRef.value) return;

  lineChart = echarts.init(lineChartRef.value);

  const hours = [];
  const visitData = [];
  const viewData = [];

  for (let i = 0; i < 50; i++) {
    const hour = 16 + i * 0.02;
    hours.push(`${Math.floor(hour)}:${String(Math.floor((hour % 1) * 60)).padStart(2, "0")}`);
    visitData.push(Math.floor(Math.random() * 200) + 50);
    viewData.push(Math.floor(Math.random() * 300) + 100);
  }

  const option = {
    tooltip: {
      trigger: "axis"
    },
    legend: {
      data: ["浏览量", "访问量"],
      top: 10
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: hours
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        name: "浏览量",
        type: "line",
        stack: "Total",
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(24, 141, 240, 0.6)" },
            { offset: 1, color: "rgba(24, 141, 240, 0.1)" }
          ])
        },
        data: viewData,
        smooth: true,
        lineStyle: {
          color: "#188df0"
        }
      },
      {
        name: "访问量",
        type: "line",
        stack: "Total",
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(46, 204, 113, 0.6)" },
            { offset: 1, color: "rgba(46, 204, 113, 0.1)" }
          ])
        },
        data: visitData,
        smooth: true,
        lineStyle: {
          color: "#2ecc71"
        }
      }
    ]
  };

  lineChart.setOption(option);
};

// 初始化词云图
const initWordCloud = () => {
  if (!wordCloudRef.value) return;

  // 模拟词云数据
  const keywords = [
    "电商",
    "购物",
    "商品",
    "优惠",
    "促销",
    "品牌",
    "质量",
    "服务",
    "物流",
    "配送",
    "支付",
    "退换",
    "评价",
    "推荐",
    "新品",
    "热销",
    "折扣",
    "满减",
    "秒杀",
    "团购",
    "会员",
    "积分",
    "客服",
    "售后",
    "手机",
    "电脑",
    "服装",
    "美妆",
    "家居",
    "食品",
    "图书",
    "运动"
  ];

  const wordCloudData = keywords.map(word => ({
    name: word,
    value: Math.floor(Math.random() * 100) + 20
  }));

  wordCloudChart = echarts.init(wordCloudRef.value);

  // 简化的词云效果（使用散点图模拟）
  const option = {
    tooltip: {
      show: false
    },
    series: [
      {
        type: "wordCloud",
        shape: "circle", // 圆形
        left: "center",
        top: "center",
        width: "90%",
        height: "90%",
        sizeRange: [12, 50], // 字号区间
        rotationRange: [-45, 45], // 旋转角度
        gridSize: 8, // 词间距
        textStyle: {
          color: () =>
            `rgb(${Math.round(Math.random() * 160) + 50}, ${Math.round(Math.random() * 160) + 50}, 255)`
        },
        emphasis: {
          textStyle: { shadowBlur: 10, shadowColor: "#333" }
        },
        data: wordCloudData.sort((a, b) => b.value - a.value)
      }
    ],
    xAxis: {
      show: false,
      type: "value",
      min: 0,
      max: 100
    },
    yAxis: {
      show: false,
      type: "value",
      min: 0,
      max: 100
    }
  };

  wordCloudChart.setOption(option);
};

// 初始化饼图
const initPieChart = () => {
  if (!pieChartRef.value) return;

  pieChart = echarts.init(pieChartRef.value);

  const option = {
    legend: {
      bottom: "2%",
      left: "center"
    },
    series: [
      {
        animationDelay() {
          return Math.random() * 100;
        },
        animationEasing: "exponentialInOut",
        animationType: "scale",
        avoidLabelOverlap: false,
        color: ["#5ab1ef", "#b6a2de", "#67e0e3", "#2ec7c9"],
        data: [
          { name: "搜索引擎", value: 1048 },
          { name: "直接访问", value: 735 },
          { name: "邮件营销", value: 580 },
          { name: "联盟广告", value: 484 }
        ],
        emphasis: {
          label: {
            fontSize: "12",
            fontWeight: "bold",
            show: true
          }
        },
        itemStyle: {
          // borderColor: '#fff',
          borderRadius: 10,
          borderWidth: 2
        },
        label: {
          position: "center",
          show: false
        },
        labelLine: {
          show: false
        },
        name: "访问来源",
        radius: ["40%", "65%"],
        type: "pie"
      }
    ],
    tooltip: {
      trigger: "item"
    }
  };

  pieChart.setOption(option);
};

// 初始化地图
const initMapChart = () => {
  if (!mapChartRef.value) return;

  mapChart = echarts.init(mapChartRef.value);

  const data = [
    { name: "北京", value: 177 },
    { name: "天津", value: 42 },
    { name: "河北", value: 102 },
    { name: "山西", value: 81 },
    { name: "内蒙古", value: 47 },
    { name: "辽宁", value: 67 },
    { name: "吉林", value: 82 },
    { name: "黑龙江", value: 123 },
    { name: "上海", value: 24 },
    { name: "江苏", value: 92 },
    { name: "浙江", value: 114 },
    { name: "安徽", value: 109 },
    { name: "福建", value: 116 },
    { name: "江西", value: 91 },
    { name: "山东", value: 119 },
    { name: "河南", value: 137 },
    { name: "湖北", value: 116 },
    { name: "湖南", value: 114 },
    { name: "重庆", value: 91 },
    { name: "四川", value: 125 },
    { name: "贵州", value: 62 },
    { name: "云南", value: 83 },
    { name: "西藏", value: 9 },
    { name: "陕西", value: 80 },
    { name: "甘肃", value: 56 },
    { name: "青海", value: 10 },
    { name: "宁夏", value: 18 },
    { name: "新疆", value: 67 },
    { name: "广东", value: 123 },
    { name: "广西", value: 59 },
    { name: "海南", value: 14 }
  ];

  // 简化的地域分布图（使用柱状图）
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "value",
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: "category",
      data: data.slice(0, 10).map(item => item.name)
    },
    series: [
      {
        name: "访问量",
        type: "bar",
        data: data.slice(0, 10).map(item => item.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: "#83bff6" },
            { offset: 0.5, color: "#188df0" },
            { offset: 1, color: "#188df0" }
          ])
        }
      }
    ]
  };

  mapChart.setOption(option);
};

// 获取排名颜色
const getRankingColor = index => {
  const colors = [
    "bg-yellow-500",
    "bg-gray-400",
    "bg-orange-500",
    "bg-blue-500",
    "bg-green-500",
    "bg-purple-500",
    "bg-pink-500"
  ];
  return colors[index] || "bg-gray-500";
};

// 改变图表时间范围
const changeChartTimeRange = range => {
  chartTimeRange.value = range;
  if (barChart) {
    const data = getBarChartData();
    barChart.setOption({
      xAxis: {
        data: data.categories
      },
      series: [
        {
          data: data.data
        }
      ]
    });
  }
};

// 窗口大小变化时重新调整图表
const handleResize = () => {
  if (barChart) barChart.resize();
  if (lineChart) lineChart.resize();
  if (wordCloudChart) wordCloudChart.resize();
  if (pieChart) pieChart.resize();
  if (mapChart) mapChart.resize();
};
// 监听窗口变化
let resizeObserver = null;
// 生命周期
onMounted(() => {
  nextTick(() => {
    initBarChart();
    initLineChart();
    initWordCloud();
    initPieChart();
    initMapChart();
    initSmallLineChart();

    resizeObserver = new ResizeObserver(handleResize);
    resizeObserver.observe(barChartRef.value);
    // window.addEventListener("resize", handleResize);
  });
});

// 监听图表时间范围变化
watch(chartTimeRange, () => {
  changeChartTimeRange(chartTimeRange.value);
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped>


/* 响应式设计 */
@media (width <= 768px) {
  .grid {
    grid-template-columns: 1fr;
  }
}

.analytics-dashboard {
  font-family: "Helvetica Neue", Arial, sans-serif;
}

/* Element Plus 样式覆盖 */
:deep(.el-button-group .el-button) {
  border-radius: 4px;
}

.line-card {
  overflow: hidden;
  border-radius: 10px;
}

:deep(.el-date-editor) {
  width: 200px;
}
</style>
